<template>
  <div class="modal" v-if="show">
    <div class="box" ref="box">
      内容

      <button>hello</button>
    </div>
  </div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref } from "vue";

const props = defineProps({
  show: Boolean,
  name: {
    default: "www",
  },
});
const emit = defineEmits(["close"]);

const box = ref(null);

function close(event) {
  console.log(event.target);
  // 判断当前触发事件的元素 等于 box 元素，则不关闭弹窗
  if (box.value && box.value.contains(event.target)) {
    return;
  }
  emit("close");
}

onMounted(() => {
  document.addEventListener("click", close, true);
});

onBeforeUnmount(() => {
  document.removeEventListener("click", close);
});
</script>

<style>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 300px;
  background-color: #fff;
}
</style>
